package com.hjtech.baselib.utils

import android.app.Activity
import android.content.Context
import com.apkfuns.logutils.LogUtils
import java.util.*


/*
 * 项目名:    RabbitCommunityExpress
 * 包名       cn.hjtech.directory.common.utils
 * 文件名:    ActivityManager
 * 创建者:    CYS
 * 创建时间:  2017/5/8 on 11:47
 * 描述:     Activity管理类
 */
class ActivityManager private constructor() {

    /**
     * 添加Activity到堆栈
     */
    @Synchronized
    fun addActivity(activity: Activity) {
        if (activityStack == null) {
            activityStack = Stack()
        }
        activityStack!!.add(activity)
        LogUtils.i("ActivityManager添加了：" + activity.javaClass.name)
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    fun currentActivity(): Activity {
        return activityStack!!.lastElement()
    }

    /**
     * 移除最后一个Activity
     */
    fun removeActivity(activity: Activity?) {
        if (activity != null) {
            activityStack!!.remove(activity)
            LogUtils.i("ActivityManager移除了：" + activity.javaClass.name)
        }
    }

    /**
     * 结束指定的Activity
     */
    @JvmOverloads
    fun finishActivity(activity: Activity? = activityStack!!.lastElement()) {
        if (activity != null) {
            activityStack!!.remove(activity)
            activity.finish()
            LogUtils.i("ActivityManager关闭了：" + activity.javaClass.name)
        }
    }

    /**
     * 结束指定类名的Activity
     */
    fun finishActivity(cls: Class<*>) {
        for (i in activityStack!!.indices) {
            if (activityStack!![i].javaClass == cls) {
                finishActivity(activityStack!![i])
                removeActivity(activityStack!![i])
                return
            }
        }
    }


    /**
     * 结束所有Activity
     */
    fun finishAllActivity() {
        for (activity in activityStack!!) {
            activity?.finish()
        }
        activityStack!!.clear()
    }


    /**
     * 退出应用程序
     */
    fun AppExit(context: Context) {
        try {
            finishAllActivity()
            val activityMgr = context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
            activityMgr.restartPackage(context.packageName)
            System.exit(0)
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    companion object {

        private var activityStack: Stack<Activity>? = null
        private var instance: ActivityManager? = null

        /**
         * 单一实例
         */
        val appInstance: ActivityManager
            @Synchronized get() {
                if (instance == null) {
                    instance = ActivityManager()
                }
                return instance!!
            }
    }
}
/**
 * 结束当前Activity（堆栈中最后一个压入的）
 */
